package org.sample.ams.apis.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.sample.ams.apis.dto.WorkersDto;
import org.sample.ams.domain.entity.AmsWorkers;
import org.sample.ams.domain.repository.WorkersRepository;
import org.springframework.data.domain.*;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.wisdom.annotation.WisdomController;
import org.wisdom.vo.PageModel;
import org.wisdom.vo.ResponseResult;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;

/**
 * 填报
 *
 * @author 张智研
 * @date 2025/05/14 15:47
 **/
@WisdomController
@RequestMapping("/workers")
@RequiredArgsConstructor
public class WorkersController {
    private final WorkersRepository workersRepository;

    @GetMapping("/list")
    ResponseResult<PageModel<WorkersDto>> list(WorkersDto workersDto) {
        Sort sort = Sort.unsorted();
        AmsWorkers workers = new AmsWorkers();
        BeanUtil.copyProperties(workersDto,workers);
        ExampleMatcher matcher =
                ExampleMatcher.matching()
                        .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<AmsWorkers> workersExample = Example.of(workers, matcher);
        Page<AmsWorkers> workersPage =
                this.workersRepository.findAll(workersExample, PageRequest.of(workersDto.getPageNumber() - 1, workersDto.getPageSize(), sort));

        PageModel<WorkersDto> pageModel = new PageModel<>();

        List<WorkersDto> workersDtoList = BeanUtil.copyToList(workersPage.getContent(),WorkersDto.class);

        pageModel.setContent(workersDtoList);
        pageModel.setTotalPages(workersPage.getTotalPages());
        pageModel.setTotalElements(workersPage.getTotalElements());
        pageModel.setPageNumber(workersPage.getNumber() + 1);
        pageModel.setPageSize(workersPage.getSize());
        return ResponseResult.ok(pageModel);
    }

    @PostMapping
    ResponseResult<WorkersDto> save(@RequestBody WorkersDto workersDto) {

        AmsWorkers workers = new AmsWorkers();
        BeanUtil.copyProperties(workersDto,workers);

        // 发送POST请求并获取响应体
        RestTemplate restTemplate = new RestTemplate();
        String url ="https://eform.cofco.com/stg-api/v1/api/getToken?appkey=demo&appsecret=123456";
//        url = "http://localhost:8081/v1/api/getToken?appkey=demo&appsecret=123456";
        ResponseEntity<JSONObject> result = restTemplate.getForEntity(url, JSONObject.class);
        String accessToken = result.getBody().getStr("data");

        HttpHeaders headers = new HttpHeaders();
        // 设置内容类型为JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("access-token", accessToken);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("templateCode",workersDto.getTemplateCode());
        jsonObject.set("templateVer",workersDto.getTemplateVer());
        JSONObject params = JSONUtil.parseObj("{\"联系人\":[{}],\"工作经历\":[{}],\"基本信息\":{\"顾问姓名\":\"冯嘉怡\"},\"项目经历\":[{}],\"培训经历\":[{}],\"学习经历\":[{}]}");
        params.getJSONObject("基本信息").set("顾问姓名",workersDto.getName());
        jsonObject.set("params",params);
        // 创建HttpEntity对象，包含请求体和头信息
        HttpEntity<Object> entity = new HttpEntity<>(jsonObject.toString(), headers);
        url ="https://eform.cofco.com/stg-api/v1/api/fillReport";
//        url = "http://localhost:8081/v1/api/fillReport";
        result = restTemplate.postForEntity(url,entity, JSONObject.class);
        String reportId = result.getBody().getJSONObject("data").getStr("id");
        workers.setReportId(reportId);
        String reportUrl = result.getBody().getJSONObject("data").getStr("url");
        reportUrl = reportUrl + "?id="+reportId + "&access-token="+accessToken;
        workers.setUrl(reportUrl);
        this.workersRepository.save(workers);
        BeanUtil.copyProperties(workers,workersDto);
        return ResponseResult.ok(workersDto);
    }

    @PostMapping("/update")
    ResponseResult<WorkersDto> update(@RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject.toJSONString(2));
        String reportId = jsonObject.getStr("id");
        AmsWorkers workers = this.workersRepository.findByReportId(reportId);
        JSONObject baseInfo = jsonObject.getJSONObject("基本信息");
        workers.setName(baseInfo.getStr("顾问姓名",""));
        workers.setSex(baseInfo.getStr("性别",""));
        if (ObjectUtil.isNotEmpty(baseInfo.getStr("出生日期",""))) {
            String rgex = "(?<=\\/OADate\\().*?(?=\\)/)";

            Pattern pattern = Pattern.compile(rgex);
            Matcher matcher = pattern.matcher(baseInfo.getStr("出生日期",""));
            String time = null;
            if (matcher.find()) {
                time = matcher.group();
            }
            BigDecimal time1 = new BigDecimal(time);
            time1 = time1.multiply(new BigDecimal(86400000)).add(new BigDecimal("-2209190400000"));
            Date a = new Date(time1.longValue());
            workers.setBirthday(DateUtil.format(a,"yyyy-MM-dd"));
        }
        workers.setNationality(baseInfo.getStr("民族",""));
        workers.setNo(baseInfo.getStr("身份证号",""));
        workers.setSchool(baseInfo.getStr("最高学历",""));
        this.workersRepository.save(workers);
        return ResponseResult.ok();
    }

    public static void main(String[] args) {
        String date = "/OADate(36872)/";
        String rgex = "(?<=\\/OADate\\().*?(?=\\)/)";

        Pattern pattern = Pattern.compile(rgex);
        Matcher matcher = pattern.matcher(date );
        String time = null;
        if (matcher.find()) {
            time = matcher.group();
        }
        BigDecimal time1 = new BigDecimal(time);
        time1 = time1.multiply(new BigDecimal(86400000)).add(new BigDecimal("-2209190400000"));
        Date a= new Date(time1.longValue());
        System.out.println(DateUtil.format(a,"yyyy-MM-dd"));
        String ss = "{\"d\":\"/OADate(36872)/\"}";
        JSONObject jsonObject = JSONUtil.parseObj(ss);
        System.out.println(jsonObject.getDate("d"));

    }


}
